var Library = function() {

    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();

    var openUserDatalist_url = $('.openUserDatalist_url').val();
    var userDatalist_url = $('.userDatalist_url').val();

    var isLoadOpenuserTable = false;
    var isLoadUserTable = false;


    // 七牛
    var upload_element = 'upload-image'; // 上传按钮的上级元素ID
    var upload_btn = 'upload-btn'; // 上传按钮的ID
    var field = $('#' + upload_btn).attr('data-field');
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var max_file_size = $('#' + upload_btn).attr('data-max_file_size');
    var extensions = $('#' + upload_btn).attr('data-extensions');
    var multi = $('#' + upload_btn).attr('data-multi');


    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                //"ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {"data": "createOper"},
                    {"data": "createDate"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [2, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var initOpenuserTable = function() {
        var table = $('#openUser-datatable');
        var libraryId = $('input[name=id]').val();

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: openUserDatalist_url,
                    data: {'id':libraryId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "p_imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 40px;height: 40px;"/></a>';
                        }
                    },
                    {"data": "p_name"},
                    {
                        "width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            html += '<input type="hidden" class="userId" value="'+row.userId+'">';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    //
                },
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    var openuserIds = $('.openuserIds').val();
                    if(openuserIds){
                        openuserIds = openuserIds + ',' + aData['userId'];
                    }else{
                        openuserIds = aData['userId'];
                    }
                    $('.openuserIds').val(openuserIds);
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });

            isLoadOpenuserTable = true;
        }

        // 删除
        table.on('click', '.delete-btn', function(event) {
            var _this = $(this);

            _this.parents('tr').remove();
            var ids = '';
            $('#openUser-datatable').find('tbody').find('tr').each(function(){
                ids += ',' + $(this).find('.userId').val();
            });
            $('.openuserIds').val(ids.substr(1));
        });
    };

    var initUserTable = function() {
        var table = $('#user-datatable');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: userDatalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "p_imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<img src="'+data+'" style="width: 40px;height: 40px;"/>';
                        }
                    },
                    {"data": "p_name"},
                    {"data": "duties"},
                    {
                        "width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            //var html = '<button type="button" class="btn btn-success select-btn">选择</button>';
                            var html = '';
                            html += '<div class="md-checkbox has-success">';
                            html += '<input type="checkbox" id="check-user'+row.id+'" class="md-check check-item" name="id[]" value="'+row.id+'" data-name="'+row.p_name+'" data-avatar="'+row.p_imgUrl+'">';
                            html += '<label for="check-user'+row.id+'">';
                            html += '<span class="inc"></span>';
                            html += '<span class="check"></span>';
                            html += '<span class="box"></span>';
                            html += '选择 ';
                            html += '</label>';
                            html += '</div>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true, // 不重新加载表格内容
                //"destroy": false,
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    var openuserIds = $('.openuserIds').val();
                    if(openuserIds.indexOf(aData['id']) >= 0) {
                        $(nRow).find('input[type=checkbox]').prop('checked', true);
                        $(nRow).find('input[type=checkbox]').prop('disabled', true);
                    }
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });

            isLoadUserTable = true;
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    var viewUser = function () {
        $('#viewUser-modal').modal('show');
        initUserTable();
    };

    // 详情页初始化
    var initDetail = function() {
        if($('#ajax-form').length > 0){
            init_openType();
        }
    };

    // 初始化 开放类型
    var init_openType = function() {
        var openType = $('.open-type').find('input[name=openType]:checked').val();
        if(openType == 1){
            $('.openUser-list').show();

            if(!isLoadOpenuserTable){
                initOpenuserTable();
            }
        }else{
            $('.openUser-list').hide();
        }
    };


    /**
     * 七牛初始化
     */
    var initUploader = function () {
        if($('#' + upload_element).length <= 0){
            return ;
        }

        var url = "";
        var qiniupercent = "";
        var uploader = upload_element;
        var pickfiles = upload_btn;
        if(max_file_size == '' || max_file_size == undefined){
            max_file_size = '1MB';
        }
        if(extensions == '' || extensions == undefined){
            extensions = 'jpg,jpeg,gif,png';
        }
        if(multi == 'false'){
            multi = false;
        }else{
            multi = true;
        }

        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                uploaderReady(data.uptoken, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi);
            }
        });
    };

    var uploaderReady = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            container: uploader,      //上传按钮的上级元素ID
            drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                        var nativeFile = file.getNative();
                        var size = nativeFile.size;
                        var type = nativeFile.type;
                        var name = nativeFile.name;

                        var pos = name.lastIndexOf('.');
                        var fileName = name.substr(0, pos);
                        $('input[name=fileName]').val(fileName);
                        //console.log(nativeFile);
                        // type: Google 是 audio/mp3; Firefox 是 audio/mpeg
                        if(size > 1024 * 1024 * 5){
                            layer.msg('最大为 5M');
                            up.removeFile(file);
                            return;
                        }

                        layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    //layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                // 删除原文件
                                var img_id = $('#' + upload_btn).find('input[name=imgId]').val();
                                var img_url = $('input[name=fileUrl]').val();
                                delOriginalImg(img_id, img_url);

                                $('input[name=fileUrl]').parent().show();
                                $('input[name=fileUrl]').val(sourceLink);
                                if($('#' + upload_btn).find('input[name=imgId]').val()) {  //已有图片
                                    $('#' + upload_btn).find('input[name=imgId]').val(data.image_id);
                                } else {
                                    $('#' + upload_btn).append('<input type="hidden" name="imgId" value="'+data.image_id+'">');
                                }
                                // imgcount++;
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };

    // 删除原图
    var delOriginalImg = function (img_id, img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
                'id' : img_id
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };


    return {
        init: function() {
            initUploader();
            initTable();
            initDetail();

            this.onEvent();
        },

        onEvent : function(){

            // 切换公开类型
            $('.openType').on('click',function () {
                init_openType();
            });

            // 添加人员
            $('.addUser-btn').on('click', function(){
                viewUser();
            });

            // 全选 / 取消全选
            $(document).find('.sellectall-btn').on('click', function(){
                var form = document.getElementById("openuser-form");
                var _this = $(this);

                var value = $(this).attr('data-value');
                if(value == 1){
                    $(form).find('.check-item').not(':disabled').prop('checked', true);
                    _this.attr('data-value', 2);
                    _this.empty().html('取消全选');
                }else{
                    $(form).find('.check-item').not(':disabled').prop('checked', false);
                    _this.attr('data-value', 1);
                    _this.empty().html('全选');
                }
            });

            // 确定添加
            $(document).find('.saveOpenuser-btn').on('click', function(){
                var form = document.getElementById("openuser-form");
                var _this = $(this);

                //if($(form).find('.check-item').filter(':checked').length <= 0){
                if($(form).find('.check-item').not(':disabled').filter(':checked').length <= 0){
                    layer.msg('请至少选择一条数据');
                    return false;
                }
                var ids = '';
                $(form).find('.check-item').not(':disabled').filter(':checked').each(function () {
                    ids += ',' + $(this).val();
                });

                ids = ids.substr(1);
                var openuserIds = $('.openuserIds').val();
                if(openuserIds){
                    openuserIds = openuserIds + ',' + ids;
                }else{
                    openuserIds = ids;
                }
                $('.openuserIds').val(openuserIds);

                $(form).find('.check-item').not(':disabled').filter(':checked').each(function () {
                    var id = $(this).val();
                    var name = $(this).data('name');
                    var avatar = $(this).data('avatar');

                    var html = '<tr role="row" class="odd">';
                        html += '<td><img src="'+avatar+'" style="width: 40px;height: 40px;"></td>';
                        html += '<td>'+name+'</td>';
                        html += '<td><button type="button" class="btn btn-danger delete-btn">删除</button><input type="hidden" class="userId" value="'+id+'"></td>';
                    html += '</tr>';

                    var table_count = $('#openUser-datatable').find('tbody').children('tr[role=row]').length;
                    if(table_count < 1){
                        $('#openUser-datatable').find('tbody').empty();
                    }
                    $('#openUser-datatable').find('tbody').append(html);
                });

                $('#viewUser-modal').modal('hide');
            });

            // 表单提交
            $('.save-btn').on('click', function(){
                var form = this.form;
                var _this = $(this);

                if(form.name.value=='') {
                    layer.msg("请输入名称!");
                    form.name.focus();
                    return;
                }
                if(form.fileUrl.value.trim() == ''){
                    layer.msg('请上传文件');
                    return false;
                }
                if(form.openType.value == 1) {
                    if(form.openuserIds.value == '') {
                        layer.msg("请添加公开人员!");
                        return;
                    }
                }


                var _data = $(form).serializeObject();
                _data.fileUrl = form.fileUrl.value;
                _this.prop("disabled", true);

                $.ajax({
                    url : save_url,
                    type : 'post',
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(_data),
                }).done(function(data) {
                    if (data.code == 1) {
                        layer.msg('保存成功');
                        window.location.href= data.url; //加载页面数据
                    } else {
                        _this.prop("disabled", false);
                        layer.msg(data.msg);
                    }
                });
            });
        }
    };

}();

$(function() {
    Library.init();
});
